<template>
  <el-container style="height: 600px; border: 1px solid #eee">
    <el-container>
      <!-- 搜索区 -->
      <el-header>
        <el-input v-model="search.code" placeholder="商品编号" style="width:300px;" />
        <el-input v-model="search.name" placeholder="商品名称" style="width:300px;" />
        <el-button type="primary" icon="el-icon-search" @click="searchGoods()">搜索</el-button>
      </el-header>
      <!-- 功能区 -->
      <el-main style="height:600px;">
        <el-row>
          <el-button type="primary" size="mini" @click="inShelves()">上架</el-button>
          <el-button type="danger" size="mini" @click="outShelves()">下架</el-button>
        </el-row>
        <!-- 表格 组件 -->
        <datatable
          :table-fomat="tableFomat"
          :table-data="tableData"
          :total="tableData.length"
          :operate-visible="false"
          @handleSelectionChange="handleSelectionChange"
        >
          <el-table-column label="规格" width="200">
            <template slot-scope="scope">
              <el-tag
                v-for="(ele,index) in scope.row.specification"
                :key="index"
                type="info"
                style="margin: 0px 2px"
              >{{ ele.name }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="是否推荐" width="200">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.recommend"
                :disabled="scope.row.goods_status == 0 ? true : false"
                active-text="是"
                inactive-text="否"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                @change="(value) => recommendChange(value,scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="商品状态" width="120">
            <template slot-scope="scope">{{ scope.row.goods_status == 0 ? '已下架' : '正在售卖' }}</template>
          </el-table-column>

          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="上架" placement="top-start">
                <el-button
                  style="font-size:20px"
                  type="primary"
                  icon="el-icon-shopping-cart-full"
                  circle
                  size="mini"
                  @click="handleShelves(scope.$index, scope.row,'handleShelvesIn')"
                />
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="下架" placement="top">
                <el-button
                  style="font-size:20px"
                  type="danger"
                  icon="el-icon-shopping-cart-2"
                  circle
                  size="mini"
                  @click="handleShelves(scope.$index, scope.row, 'handleShelvesOut')"
                />
              </el-tooltip>
            </template>
          </el-table-column>
        </datatable>
      </el-main>
    </el-container>
  </el-container>
</template>
<style>
/* 容器头部 和  */
.el-header {
  line-height: 60px;
}
.el-aside {
  width: 200px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  color: #333;
  background-color: white;
}
</style>
<script>
import datatable from '@/views/my-views/components/table'
import goods from '@/sql/table-field/index'
import { tsFormatTime } from '@/tools/util'
import { mapGetters } from 'vuex'
export default {
  name: 'GoodsShelves',
  components: {
    datatable
  },
  data() {
    return {
      switchs: [],
      // 上下架的表单
      shelvesForm: {
        _id: '',
        goods_status: 0
      },
      // 解决notice通知栏覆盖问题
      notifyPromise: Promise.resolve(),
      // 搜索输入框的值
      search: {
        name: '',
        code: ''
      },
      // 表格显示格式(列名以及列对应显示的数据)
      tableFomat: goods.goodsShelves,
      // 表格数据
      tableData: [],
      // 当前表格选中的数据
      multipleSelection: []
    }
  },
  computed: {
    // 从store中的getters中获取数据(store/getters.js)
    ...mapGetters(['goodsShelves'])
  },
  mounted() {
    // 如果state中有数据则从state中读取
    if (this.goodsShelves.length !== 0) {
      // 使用缓存
      this.tableData = this.goodsShelves
    } else {
      // 获取商品列表
      this.getGoodsShelvesList()
    }
  },
  methods: {
    // 数据库数据转换为前端显示数据格式
    dataBaseToFormData(value) {
      value.create_time = tsFormatTime(value.create_time, 'Y-M-D h:m:s')
      value.update_time = tsFormatTime(value.update_time, 'Y-M-D h:m:s')
      return value
    },
    // tip提示方法
    tipformat(res, type, type_name) {
      if (res.errcode !== 0) {
        this.notifyPromise = this.notifyPromise
          .then(this.$nextTick)
          .then(() => {
            this.$notify.error({
              title: `${type}商品失败`,
              message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
              duration: 0
            })
          })
      } else {
        this.notifyPromise = this.notifyPromise
          .then(this.$nextTick)
          .then(() => {
            this.$notify({
              title: `${type}商品成功`,
              message: `${type_name}--商品${type}成功`,
              type: 'success',
              duration: 6000
            })
          })
        // 重新从数据库获取数据
        this.getGoodsShelvesList()
      }
    },
    // 错误请求消息提示规范
    catchError(type, err) {
      this.$notify.error({
        title: `${type}商品请求失败`,
        message: err,
        duration: 0
      })
    },
    searchGoods() {
      const type = '搜索'
      this.$store
        .dispatch('searchGoodsShelves', this.search)
        .then(res => {
          if (res.errcode !== 0) {
            if (res.errcode === 42001) {
              this.$notify.error({
                title: 'Access_token过期,请重新刷登录获取',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            } else {
              this.$notify.error({
                title: '获取商品列表失败',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            }
          } else {
            this.tableData = JSON.parse(res.resp_data).data.list
            this.tableData.map(res => {
              this.dataBaseToFormData(res)
            })
          }
        })
        .catch(err => {
          // 错误请求消息提示
          this.catchError(type, err)
        })
    },
    // 获取商品上下架列表的方法
    getGoodsShelvesList() {
      const type = '获取'
      this.$store
        .dispatch('getGoodsListLinkGoodsSku')
        .then(res => {
          if (res.errcode !== 0) {
            if (res.errcode === 42001) {
              this.$notify.error({
                title: 'Access_token过期,请重新刷登录获取',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            } else {
              this.$notify.error({
                title: '获取商品列表失败',
                message: `错误代码:${res.errcode} 错误消息:${res.errmsg}`,
                duration: 0
              })
            }
          } else {
            this.tableData = JSON.parse(res.resp_data).data.list
            this.tableData.map(res => {
              this.dataBaseToFormData(res)
            })
            this.$store.commit('setGoodsShelves', this.tableData)
          }
        })
        .catch(err => {
          this.catchError(type, err)
        })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    updateGoodsStatus(type, row) {
      this.$store
        .dispatch('updateGoodsStatus', this.shelvesForm)
        .then(res => {
          this.tipformat(res, type, row.goods_name)
        })
        .catch(err => {
          this.catchError(type, err)
        })
    },
    recommendChange(value, row) {
      let type = ''
      if (value === 1) {
        type = '成功推荐'
      } else {
        type = '取消推荐'
      }
      const formData = row
      const recommendStatus = value
      this.$store
        .dispatch('updateGoodsRecommend', { formData, recommendStatus })
        .then(res => {
          this.tipformat(res, type, row.goods_name)
        })
        .catch(err => {
          this.catchError(type, err)
        })
    },
    // 每列的上下架
    handleShelves(index, row, name) {
      this.shelvesForm._id = row._id
      if (name === 'handleShelvesIn') {
        const type = '上架'
        // 修改商品的状态
        this.shelvesForm.goods_status = 1
        if (row.goods_status === 0) {
          this.updateGoodsStatus(type, row)
        } else {
          this.$message({
            message: '商品已经上架',
            type: 'warning'
          })
        }
      } else if (name === 'handleShelvesOut') {
        const type = '下架'
        this.shelvesForm.goods_status = 0
        if (row.goods_status === 1) {
          this.updateGoodsStatus(type, row)
        } else {
          this.$message({
            message: '商品已经下架',
            type: 'warning'
          })
        }
      }
    },
    // 头部的下架
    outShelves() {
      const type = '下架'
      let formDatas = []
      // 需要下架的
      formDatas = this.multipleSelection.filter(res => res.goods_status === 1)
      if (formDatas.length >= 1) {
        const goods_status = 0
        this.$store
          .dispatch('updateGoodsStatusMore', { formDatas, goods_status })
          .then(res => {
            for (let i = 0; i < formDatas.length; i++) {
              this.tipformat(res[i], type, formDatas[i].goods_name)
            }
          })
          .catch(err => {
            this.catchError(type, err)
          })
      } else {
        this.$message({
          message: '请选择正在售卖的商品',
          type: 'warning'
        })
      }
    },
    // 头部的上架
    inShelves() {
      const type = '上架'
      // 需要上架的 过滤掉已经在售卖的
      let formDatas = []
      formDatas = this.multipleSelection.filter(res => res.goods_status === 0)
      if (formDatas.length >= 1) {
        const goods_status = 1
        this.$store
          .dispatch('updateGoodsStatusMore', { formDatas, goods_status })
          .then(res => {
            for (let i = 0; i < formDatas.length; i++) {
              this.tipformat(res[i], type, formDatas[i].goods_name)
            }
          })
          .catch(err => {
            this.catchError(type, err)
          })
      } else {
        this.$message({
          message: '请选择已经下架的商品',
          type: 'warning'
        })
      }
    }
  }
}
</script>
